import sys
import sklearn
import numpy as np
import pandas as pd
F_FILE_PATH = "f_train.csv"
SYS_ENCODING = "ANSI"   # 实际运行时发现在Windows系统下打开csv文件需要指定编码

class Model():
    def __init__(self,**kwargs):
        from sklearn import datasets
        from sklearn.tree import DecisionTreeClassifier as DTC,export_graphviz
        from sklearn.ensemble import RandomForestClassifier
        from sklearn.ensemble import GradientBoostingClassifier
        # self.model = RandomForestClassifier(n_estimators=150)
        self.model = GradientBoostingClassifier(learning_rate=0.2,max_depth=3)  
    def train(self,X,y):
        self.model.fit(X,y)
        return self.model
    def predict(self,X):
        pred_y = self.model.predict(X)
        return pred_y
    def score(self,pred_y,y_test):
        hit_positive = 0
        predict_positive = 0
        total_positive = 0
        hit_total = 0
        for i in range(len(pred_y)):
            pred_y[i] = round(pred_y[i])
            if(y_test[i] == 1):
                total_positive = total_positive + 1
                if(pred_y[i] == y_test[i]):
                    hit_positive = hit_positive + 1
            # if(Y_predict[i] == Y[i+train_size]):
            #     hit_total = hit_total + 1
            if(pred_y[i] == 1):
                predict_positive = predict_positive + 1
        P = hit_positive / predict_positive
        R = hit_positive / total_positive
        F1 = (2 * P * R) / (P + R)
        return F1

if __name__ == '__main__':
    f_model = Model()
    # 从f_train.csv读取原始数据
    df = pd.read_csv(F_FILE_PATH, encoding=SYS_ENCODING)

    # 用平均值填充缺失位置，并写进新的文件中
    fill_dict = {}
    mean_list = ['RBP4','孕前体重','孕前BMI','糖筛孕周','VAR00007','wbc','Cr','BUN','CHO','TG','HDLC','LDLC','ApoA1','APoB','Lpa','hsCRP']
    cols = list(df.columns.values)
    train_mean = df.mean(axis = 0, skipna = True)
    for i in range(1,len(cols) - 1):
        col = cols[i]
        if(col in mean_list):   # mean_list中的列填充平均值
            fill_dict[col] = train_mean[i]
        elif(col == 'BMI分类'): # BMI分类填充零
            fill_dict[col] = 0
        else:                   # 其余列填充平均值取整
            fill_dict[col] = round(train_mean[i])
    # print(fill_dict)
    df.fillna(fill_dict,inplace = True)
    # df.to_csv("f_after_wash.csv",encoding = SYS_ENCODING,index = 0)

    # 从清洗后的csv文件读取训练数据
    # df = pd.read_csv('f_after_wash.csv',encoding = SYS_ENCODING)
    df = df.iloc[:,1:]
    cols = list(df.columns.values)
    cols.remove("label")
    X_train = df[cols]
    Y_train = df["label"]


    # 训练模型
    f_model.train(X_train, Y_train)

    # 从系统参数中获取测试文件，清洗之后进行预测
    df = pd.read_csv(sys.argv[1],encoding=SYS_ENCODING)
    # print(fill_dict)
    df.fillna(fill_dict,inplace = True)
    df = df.iloc[:,1:]
    cols = list(df.columns.values)
    cols.remove('label')
    X_test = df[cols]
    Y_test = df['label']
    Y_predict = f_model.predict(X_test)
    point = f_model.score(Y_predict,Y_test)
    print("the F1 is : ",point)

